package com.isunland.managesystem.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.isunland.managesystem.R;
import com.isunland.managesystem.base.BaseConfirmDialogFragment;
import com.isunland.managesystem.base.BaseNetworkDialogFragment;
import com.isunland.managesystem.base.BaseTimeDialogFragment;
import com.isunland.managesystem.base.BaseVolleyActivity;
import com.isunland.managesystem.base.BaseYMDTimeDialogFragment;
import com.isunland.managesystem.common.ApiConst;
import com.isunland.managesystem.common.VolleyResponse;
import com.isunland.managesystem.entity.CurrentUser;
import com.isunland.managesystem.entity.CustomerDialog;
import com.isunland.managesystem.entity.SuccessMessage;
import com.isunland.managesystem.entity.WeekPlanAppointer;
import com.isunland.managesystem.utils.DateUtil;
import com.isunland.managesystem.utils.LogUtil;
import com.isunland.managesystem.utils.MyDateUtil;
import com.isunland.managesystem.utils.MyUtils;
import com.isunland.managesystem.utils.ToastUtil;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;
import org.json.JSONException;

public class TemproryPlanFragment extends Fragment implements OnClickListener {

  protected static final String TAG = TemproryPlanFragment.class.getSimpleName();
  /**
   * 本阶段完成时间
   */
  private static final int REQUEST_CHOOSE_TIME = 0;
  private static final int REQUEST_DELETE_TEMPPLAN = 1;
  /**
   * 要求完成时间
   */
  private static final int REQUEST_ACQUIRE_FINISHTIME = 2;
  /**
   * 委派人
   */
  private static final int REQUEST_CHOOSE_APOINTER = 3;
  /**
   * 计划类别
   */
  private static final int REQUEST_PLAN_KIND = 4;
  private static final int REQUEST_CHOOSE_EXECUTOR = 5;
  private BaseVolleyActivity mActivity;
  private TextView mTvProgressFinishTime;// 本阶段完成时间
  private EditText mEtProgressDegree;// 完成度
  private EditText mEtProgressWorkTime;// 所用工时
  private EditText mEtProgressContent;// 完成情况
  private EditText mEtPlanContent;// 计划内容
  private TextView mTvPlanAppointer;// 委派人
  private TextView mTvRuquestTime;// 要求完成时间
  private TextView mTvPlanKind;// 计划类别
  private TextView mtvExecutorAddWorkProcess;//执行人
  private String mId;
  /**
   * 委派人
   */
  private String mApointer;
  /**
   * 委派人JobNo
   */
  private String mApointerJobNo;

  /**
   * 工作类别名称
   */
  private String mPlanKindName;
  /**
   * 工作类别编码
   */
  private String mPlanKindCode;
  /**
   * 要求完成时间
   */
  private String mAcquireTime;
  private String mIfEnd = "F";
  private String mExecutor;//执行人
  private String mExecutorJobNo;

  @Override public void onCreate(Bundle savedInstanceState) {
    setHasOptionsMenu(true);
    mActivity = (BaseVolleyActivity) getActivity();
    ActionBar actionBar = mActivity.getSupportActionBar();
    if (actionBar != null) {
      actionBar.setTitle(R.string.plan_temp);

      if (NavUtils.getParentActivityName(getActivity()) != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
      }
    }
    mId = UUID.randomUUID().toString();
    super.onCreate(savedInstanceState);
  }

  @Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_temporary_task, container, false);
    initView(view);
    volleyPostAppointer();
    return view;
  }

  private void initView(View view) {
    mTvPlanAppointer = (TextView) view.findViewById(R.id.et_putAppointer_addWorkProcess);
    mTvRuquestTime = (TextView) view.findViewById(R.id.et_putRequestTime_addWorkProcess);
    mTvPlanKind = (TextView) view.findViewById(R.id.et_putPlanClass_addWorkProcess);
    mEtPlanContent = (EditText) view.findViewById(R.id.et_putPlanContent_addWorkProcess);
    mTvProgressFinishTime = (TextView) view.findViewById(R.id.et_putFinishTime_addWorkProcess);
    mEtProgressWorkTime = (EditText) view.findViewById(R.id.et_putUseTime_addWorkProcess);
    mEtProgressDegree = (EditText) view.findViewById(R.id.et_putFinishPercent_addWorkProcess);
    mEtProgressContent = (EditText) view.findViewById(R.id.et_putFinishCondition_addWorkProcess);
    mtvExecutorAddWorkProcess = (TextView) view.findViewById(R.id.tv_executor_addWorkProcess);

        /*
      本阶段完成时间
     */
    RadioGroup mRgIsFinish = (RadioGroup) view.findViewById(R.id.rg_isFinish_workProcess);
    RadioButton mRbFalse = (RadioButton) view.findViewById(R.id.rb_false_workProcess);
    mRbFalse.setChecked(true);
    mRgIsFinish.setOnCheckedChangeListener(new OnCheckedChangeListener() {

      @Override public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
          case R.id.rb_true_workProcess:
            mIfEnd = "T";
            mEtProgressDegree.setText(R.string.oneHundred);
            mEtProgressDegree.setEnabled(false);

            break;
          case R.id.rb_false_workProcess:
            mIfEnd = "F";
            mEtProgressDegree.setText("0");
            mEtProgressDegree.setEnabled(true);
            break;

          default:
            break;
        }
      }
    });

    mEtProgressWorkTime.setText("0.0");
    //mTvPlanAppointer.setText(CurrentUser.newInstance(getActivity()).getRealName());
    mtvExecutorAddWorkProcess.setText(CurrentUser.newInstance(getActivity()).getRealName());

    mTvProgressFinishTime.setOnClickListener(this);
    mTvRuquestTime.setOnClickListener(this);
    mTvPlanAppointer.setOnClickListener(this);
    mTvPlanKind.setOnClickListener(this);
    //mtvExecutorAddWorkProcess.setOnClickListener(this);
    mAcquireTime = MyDateUtil.parseDateToString(new Date());
    mTvRuquestTime.setText(mAcquireTime);
  }

  @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    inflater.inflate(R.menu.menu_confirm, menu);
  }

  /**
   * 获取委派人，默认为部门领导
   */
  private void volleyPostAppointer() {
    HashMap<String, String> params = new HashMap<>();
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_WEEK_APPOINTER);
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        WeekPlanAppointer appointer = new Gson().fromJson(arg0, WeekPlanAppointer.class);
        mApointer = appointer.getName();
        mApointerJobNo = appointer.getJobno();
        mTvPlanAppointer.setText(mApointer);
        //LogUtil.i("arg0=====" + arg0);
      }

      @Override public void onVolleyError(VolleyError arg0) {
        LogUtil.e("arg0===" + arg0);
      }
    });
  }

  // 判断要填写的是否填写完整及对于书写的验证
  private void saveWorkProcessEdit() {
    boolean isEmpty = MyUtils.isEmptyText(mTvPlanAppointer)
        || MyUtils.isEmptyText(mTvRuquestTime)
        || MyUtils.isEmptyText(mTvPlanKind)
        || MyUtils.isEmptyText(mEtPlanContent);

    if (isEmpty) {
      Toast.makeText(getActivity(), R.string.notComplete, Toast.LENGTH_SHORT).show();
      return;
    }

    AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
    dialog.setTitle(R.string.restart_title);
    dialog.setMessage(R.string.ifSureSave);
    dialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        volleyPostSave();
      }
    });

    dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

      @Override public void onClick(DialogInterface dialog, int which) {
        dialog.dismiss();
      }
    });
    dialog.create().show();
  }

  private void volleyPostSave() {
    MyUtils.showDialogLoading(getActivity(), R.string.loadingSubmit);
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_TEMPORARY_PLAN);

    HashMap<String, String> mTemporaryPlan = new HashMap<>();

    String mPlanContentDesc = mEtPlanContent.getText().toString();
    if (null == mApointer) {
      mApointer = CurrentUser.newInstance(getActivity()).getRealName();
    }
    if (null == mApointerJobNo) {
      mApointerJobNo = CurrentUser.newInstance(getActivity()).getJobNumber();
    }

    if (TextUtils.isEmpty(mExecutor)) {
      mExecutor = CurrentUser.newInstance(getActivity()).getRealName();
    }

    if (TextUtils.isEmpty(mExecutorJobNo)) {
      mExecutorJobNo = CurrentUser.newInstance(getActivity()).getJobNumber();
    }
    mTemporaryPlan.put("id", mId);
    mTemporaryPlan.put("taskManName", mApointer);
    mTemporaryPlan.put("taskManId", mApointerJobNo);
    mTemporaryPlan.put("planEsteTime", mAcquireTime);
    mTemporaryPlan.put("planKindName", mPlanKindName);
    mTemporaryPlan.put("planKindCode", mPlanKindCode);
    mTemporaryPlan.put("planContentDesc", mPlanContentDesc);
    mTemporaryPlan.put("excManId", mExecutorJobNo);
    mTemporaryPlan.put("excManName", mExecutor);
    LogUtil.i(TAG, "params=" + mTemporaryPlan.toString());

    mActivity.volleyPost(url, mTemporaryPlan, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage workProcess;
        try {
          MyUtils.dismissDialog();
          LogUtil.i(TAG, "response=" + arg0);
          workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
          if (null == workProcess || null == workProcess.getResult()) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          String successType = workProcess.getResult();
          if (successType.equals(SuccessMessage.FAILURE)) {
            ToastUtil.show(R.string.failure_operation);
            return;
          }
          if (successType.equals(SuccessMessage.SUCCESS)) {

            boolean flag = TextUtils.isEmpty(mEtProgressDegree.getText().toString().trim())
                && TextUtils.isEmpty(mTvProgressFinishTime.getText().toString())
                && TextUtils.isEmpty(mEtProgressContent.getText().toString().trim());
            if (flag) {
              ToastUtil.show(R.string.addTempPlan);
              //							ToastUtil.show(R.string.success_operation);
              // 成功后跳转到进展情况登记页面.
              getActivity().setResult(Activity.RESULT_OK);
              getActivity().finish();
              return;
            }
            boolean part = TextUtils.isEmpty(mEtProgressDegree.getText().toString().trim())
                || TextUtils.isEmpty(mTvProgressFinishTime.getText().toString())
                || TextUtils.isEmpty(mEtProgressContent.getText().toString().trim());
            if (part) {
              ToastUtil.show(R.string.completeWriteWrokProgress);
            } else {
              //计划保存成功，进展情况都不为空。完成度大于0，小于100.
              // 对输入完成度进行校验
              String completePercent = mEtProgressDegree.getText().toString();
              int percent = Integer.parseInt(completePercent);
              if (percent < 0 || percent > 100) {
                Toast.makeText(getActivity(), R.string.finishPercentError, Toast.LENGTH_SHORT)
                    .show();
                return;
              }

              //如果未完成，完成度不能填写100

              String finishDegree = mEtProgressDegree.getText().toString().trim();
              int degree = Integer.parseInt(finishDegree);
              if ("F".equalsIgnoreCase(mIfEnd) && degree == 100) {
                ToastUtil.show(R.string.chooseBrforeHandr);
                return;
              }

              volleyPostSaveEdit();
            }
          }
        } catch (JsonSyntaxException e) {
          e.printStackTrace();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        // Auto-generated method stub

      }
    });
  }

  protected void volleyPostSaveEdit() {
    String url = ApiConst.getAbsoluteUrl(ApiConst.URL_PROGRESS);
    HashMap<String, String> params = new HashMap<>();
    String completeTime = mTvProgressFinishTime.getText().toString();
    //String completePercent = mEtProgressDegree.getText().toString();
    String completePercent;

    try {
      int percent = Integer.parseInt(mEtProgressDegree.getText().toString().trim());
      completePercent = percent + "";
    } catch (Exception e) {
      e.printStackTrace();
      completePercent = "0";
    }

    String completeUseTime = mEtProgressWorkTime.getText().toString();
    String completeCondition = mEtProgressContent.getText().toString();
    params.put("mainid", mId);
    params.put("ifEnd", mIfEnd);
    params.put("completeDate", completeTime);
    params.put("excDesc", completeCondition);
    params.put("rateCurrent", completePercent);
    if (TextUtils.isEmpty(completeUseTime)) {
      params.put("workTimeNum", "0");
    } else {
      params.put("workTimeNum", completeUseTime);
    }
    mActivity.volleyPost(url, params, new VolleyResponse() {

      @Override public void onVolleyResponse(String arg0) throws JSONException {
        SuccessMessage workProcess = new Gson().fromJson(arg0, SuccessMessage.class);
        String successType = workProcess.getResult();
        if (successType.equals(SuccessMessage.FAILURE)) {
          ToastUtil.show(R.string.failure_operation);
          return;
        }
        if (successType.equals(SuccessMessage.SUCCESS)) {
          ToastUtil.show(R.string.success_operation);
          mEtProgressDegree.setText("");
          mEtProgressWorkTime.setText("");
          mEtProgressContent.setText("");
          mTvProgressFinishTime.setText("");
          // 如果工作计划已完成，就刷新工作计划列表。
          if (mIfEnd.equals("T")) {
            getActivity().setResult(Activity.RESULT_OK);
            getActivity().finish();
          }
          getActivity().setResult(Activity.RESULT_OK);
          getActivity().finish();
        }
      }

      @Override public void onVolleyError(VolleyError arg0) {
        Toast.makeText(getActivity(), R.string.failure_operation, Toast.LENGTH_SHORT).show();
        LogUtil.i("" + arg0);
      }
    });
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
      case android.R.id.home:
        if (NavUtils.getParentActivityName(getActivity()) != null) {
          NavUtils.navigateUpFromSameTask(getActivity());
        }
        break;
      case R.id.menu_item_confirm:
        saveWorkProcessEdit();

      default:
        return super.onOptionsItemSelected(item);
    }
    return super.onOptionsItemSelected(item);
  }

  @Override public void onClick(View arg0) {
    switch (arg0.getId()) {
      case R.id.et_putFinishTime_addWorkProcess:
        showDialog(REQUEST_CHOOSE_TIME, new Date());
        break;

      case R.id.et_putAppointer_addWorkProcess:
        Intent i = new Intent(getActivity(), AppointerListActivity.class);
        startActivityForResult(i, REQUEST_CHOOSE_APOINTER);
        break;
      case R.id.et_putPlanClass_addWorkProcess:
        showDialog(REQUEST_PLAN_KIND, null);
        break;
      case R.id.et_putRequestTime_addWorkProcess:
        showDialog(REQUEST_ACQUIRE_FINISHTIME, new Date());
        break;
      case R.id.tv_executor_addWorkProcess:
        Intent intent = new Intent(getActivity(), AppointerListActivity.class);
        startActivityForResult(intent, REQUEST_CHOOSE_EXECUTOR);
        break;
      default:
        break;
    }
  }

  /**
   * 显示时间对话框
   *
   * @param requestCode 请求码
   * @param date 对话框初始显示时间
   */
  public void showDialog(int requestCode, Date date) {

    DialogFragment dialog = null;
    FragmentManager fm = getActivity().getSupportFragmentManager();
    switch (requestCode) {
      case REQUEST_CHOOSE_TIME:// 本阶段完成时间.
        dialog = WorkProgressTimeDialogFragment.newInstance(date, R.string.chooseThisStageTime);
        break;

      case REQUEST_DELETE_TEMPPLAN:
        dialog = BaseConfirmDialogFragment.newInstance(R.string.deleteConfirm);
        break;
      case REQUEST_ACQUIRE_FINISHTIME:
        dialog = new BaseYMDTimeDialogFragment();
        break;

      case REQUEST_PLAN_KIND:
        Intent intent = new Intent(getActivity(), PlanKindListActivity.class);
        startActivityForResult(intent, requestCode);
        return;
      default:
        break;
    }
    if (dialog != null) {
      dialog.setTargetFragment(TemproryPlanFragment.this, requestCode);
      dialog.show(fm, "");
    }
  }

  @Override public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != Activity.RESULT_OK) return;
    if (requestCode == REQUEST_CHOOSE_TIME && data != null) {
      Date chooseDate = (Date) data.getSerializableExtra(BaseTimeDialogFragment.EXTRA_DATE);
      String chooseDateString = DateUtil.dateToString(chooseDate);
      mTvProgressFinishTime.setText(chooseDateString);
      return;
    }

    if (requestCode == REQUEST_ACQUIRE_FINISHTIME && data != null) {
      Date acquireDate = (Date) data.getSerializableExtra(BaseYMDTimeDialogFragment.EXTRA_DATE);
      mAcquireTime = DateUtil.dateToString(acquireDate, DateUtil.TYPE_DATE);
      mTvRuquestTime.setText(mAcquireTime);

      return;
    }

    if (requestCode == REQUEST_PLAN_KIND && data != null) {
      CustomerDialog planKind =
          (CustomerDialog) data.getSerializableExtra(BaseNetworkDialogFragment.EXTRA_VALUE);
      mPlanKindName = planKind.getName();
      mPlanKindCode = planKind.getId();
      mTvPlanKind.setText(mPlanKindName);
      return;
    }

    if (requestCode == REQUEST_CHOOSE_APOINTER && data != null) {
      CustomerDialog customer =
          (CustomerDialog) data.getSerializableExtra(AppointerListFragment.EXTRA_VALUE);
      mApointer = customer.getName();
      mApointerJobNo = customer.getId();
      // clear代表清空所选 委派人.
      if (mApointerJobNo != null && !mApointerJobNo.equalsIgnoreCase("clear")) {
        mTvPlanAppointer.setText(mApointer);
      } else {
        mTvPlanAppointer.setText("");
      }
    }

    if (requestCode == REQUEST_CHOOSE_EXECUTOR && data != null) {
      CustomerDialog exector =
          (CustomerDialog) data.getSerializableExtra(AppointerListFragment.EXTRA_VALUE);
      mExecutor = exector.getName();
      mExecutorJobNo = exector.getId();
      // clear代表清空所选 委派人.
      if (mExecutorJobNo != null && !mExecutorJobNo.equalsIgnoreCase("clear")) {
        mtvExecutorAddWorkProcess.setText(mExecutor);
      } else {
        mtvExecutorAddWorkProcess.setText("");
      }

      return;
    }
    super.onActivityResult(requestCode, resultCode, data);
  }
}
